import { Body, Controller, Delete, Get, Param, Post, Put, UseGuards } from '@nestjs/common'
import { AdminGuard } from 'src/core/admin.guard'
import { AddAzureAppReq, QueryAzureApp, UpdateAzureAppReq } from 'src/dtos/azure-app.dto'
import { AzureAppOAuthService } from 'src/services/azure-app-oauth.service'
import { AzureAppRenewService } from 'src/services/azure-app-renew.service'
import { AzureAppService } from 'src/services/azure-app.service'

@Controller('azure-app')
@UseGuards(AdminGuard)
export class AzureAppController {

  constructor(
    private readonly azureAppService: AzureAppService,
    private readonly azureAppOAuthService: AzureAppOAuthService,
    private readonly azureAppRenewService: AzureAppRenewService,
  ) { }

  @Get()
  public query() {
    let apps = this.azureAppService.query() as QueryAzureApp[]
    for (const app of apps) {
      app.authUrl = this.azureAppOAuthService.getAuthUrlByApp(app)
      if (app.msToken) {
        if (new Date().getTime() >= app.msToken.expires_ts) {
          app.authorizeStatus = 'unauthorized'
        } else {
          if (this.azureAppOAuthService.getRefreshTokenStatus(app.clientId)) {
            app.authorizeStatus = 'refreshing'
          } else {
            app.authorizeStatus = 'stopped'
          }
        }
        let rennew = this.azureAppRenewService.getRenewInfo(app.clientId)
        app.renewStatus = rennew && rennew.running ? 'running' : 'stopped'
      } else {
        app.authorizeStatus = 'unauthorized'
        app.renewStatus = 'stopped'
      }
    }
    return apps
  }

  @Post()
  public add(@Body() dto: AddAzureAppReq) {
    return this.azureAppService.add(dto)
  }

  @Put()
  public update(@Body() dto: UpdateAzureAppReq) {
    return this.azureAppService.update(dto)
  }

  @Delete(':clientId')
  public delete(@Param('clientId') clientId: string) {
    return this.azureAppService.delete(clientId)
  }

}
